package com.eastcom.mystope.daemon.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.eastcom.mystope.daemon.extern.db.config.Record;
import com.eastcom.mystope.daemon.extern.db.config.Sql;
import com.eastcom.mystope.daemon.extern.db.config.SrcResource;
import com.eastcom.mystope.daemon.extern.db.context.TaskContext;
import com.eastcom.mystope.daemon.extern.db.provider.DefaultSqlContextProvider;

public class TaskUtil<T> {
	private static Log logger = LogFactory.getLog(TaskUtil.class);
	public void save(String path, T javaObject){  
		FileOutputStream fos = null; 
		ObjectOutputStream oos = null; 
		File f = new File(path); 
		try { 
			fos = new FileOutputStream(f); 
			oos = new ObjectOutputStream(fos); 
			oos.writeObject(javaObject);    //括号内参数为要保存java对象 
		} catch (FileNotFoundException e) { 
			e.printStackTrace(); 
		} catch (IOException e) { 
			e.printStackTrace(); 
		}finally{ 
			try { 
				oos.close(); 
				fos.close(); 
			} catch (IOException e) { 
				e.printStackTrace(); 
			} 
		}    
	} 

	public T open(String path){ 
		FileInputStream fis = null; 
		ObjectInputStream ois = null;    
		File f = new File(path); 
		try { 
			fis = new FileInputStream(f); 
			ois = new ObjectInputStream(fis); 
			T object = (T)ois.readObject();//强制类型转换 
			return object;
		} catch (FileNotFoundException e) { 
			e.printStackTrace(); 
		} catch (IOException e) { 
			e.printStackTrace(); 
		} catch (ClassNotFoundException e) { 
			e.printStackTrace(); 
		}finally{ 
			try { 
				ois.close(); 
				fis.close(); 
			} catch (IOException e) { 
				e.printStackTrace(); 
			} 
		}
		return null; 
	} 

	/**
	 * @param cmmand: shell 命令  如"ls" 或"ls -1";
	 * @param directory:命令执行路径  如"/" ;
	 * @return
	 */
	public static String shellExecute(String [] cmmand,String directory){
		String result = ""; 
		try {
			ProcessBuilder builder = new ProcessBuilder(cmmand); 
			if ( directory != null ) 
				builder.directory ( new File ( directory ) ) ; 
			builder.redirectErrorStream (true) ; 
			Process process = builder.start ( ) ;
			//得到命令执行后的结果 
			InputStream is = process.getInputStream ( ) ; 
			byte[] buffer = new byte[1024] ; 
			while ( is.read(buffer) != -1 ) { 
				result = result + new String (buffer) ; 
			} 
			is.close ( ) ; 
		} catch ( Exception e ) { 
			e.printStackTrace ( ) ; 
		} 
		return result ; 
	}

	public static Record getRecordByNewTime(String taskName,Record record,Timestamp time) throws IOException, ClassNotFoundException{
		logger.debug(record);
//		List<String> sqlNameList = record.getSqlNameList();
		Record recordNew = record.deepClone();
//		recordNew.setSqlNameList(new ArrayList<String>());
		List<SrcResource> srcResourceList = recordNew.getSrcResourceConfig().getSrcResource();
		for(SrcResource srcResource: srcResourceList){
			String sqlName = srcResource.getSqlString().trim();
			Sql sql = TaskContext.sqlInfoMap.get(taskName+"_"+sqlName);
			logger.debug(taskName+"_"+sqlName+"--"+sql);
			Sql sqlNew = sql.deepClone();
			String sqlNameNew = sqlName+"_new_"+time.getTime();
			sqlNew.setName(sqlNameNew);
			TaskContext.sqlInfoMap.put(taskName+"_new_"+time.getTime()+"_"+sqlNew.getName(), sqlNew);
			logger.debug(taskName+"_"+sqlNew.getName());
			srcResource.setSqlString(sqlNameNew);
			DefaultSqlContextProvider sqlContextProvider = sql.getSqlParamProvider();
			List<Object> paramBegin = sqlContextProvider.getAutoParamBegin();
			List<Object> valueBegin = sqlContextProvider.getAutoValueBegin();
			List<Long> paramIncreamentList = sqlContextProvider.getAutoParamIncreament();
			
			
			DefaultSqlContextProvider sqlContextProviderNew = sqlNew.getSqlParamProvider();
			List<Object> lastParam = sqlContextProviderNew.getLastAutoParam();
			List<Object> lastValue = sqlContextProviderNew.getLastAutoValue();
			for(int i = 0; i < paramBegin.size(); i++){
				lastParam.set(i, paramBegin.get(i));
			}
			for(int i = 0; i < valueBegin.size(); i++){
				lastValue.set(i, valueBegin.get(i));
			}
			
			for(int i = 0; i < paramBegin.size(); i++){
				Object param = paramBegin.get(i);
				if(param instanceof Timestamp){
					long increament = paramIncreamentList.get(i);
					Timestamp beginTime = (Timestamp) param;
					//估算时间
					long cycles = (time.getTime()-beginTime.getTime())/increament;
					logger.debug("cycles="+cycles);
					for(int j = 0; j < Math.abs(cycles); j++){
						sqlContextProviderNew.updateSql(sqlNew);
					}
				}
			}
		}
		return recordNew;
	}
	
	public static Record updateRecordByTime(String taskName,Record record) throws IOException, ClassNotFoundException{
		logger.debug(record);
//		List<String> sqlNameList = record.getSqlNameList();
//		Record recordNew = record.deepClone();
//		recordNew.setSqlNameList(new ArrayList<String>());
		Timestamp time = record.getMaxDstTime();
		if(time == null){
			logger.debug("abcdefg");
			return record;
		}
		List<SrcResource> srcResourceList = record.getSrcResourceConfig().getSrcResource();
		for(SrcResource srcResource: srcResourceList){
			String sqlName = srcResource.getSqlString();
			logger.debug("sdfdsfggggggggggg"+sqlName);
			Sql sql = TaskContext.sqlInfoMap.get(taskName+"_"+sqlName);
			logger.debug(taskName+"_"+sqlName+"--"+sql);
//			Sql sqlNew = sql.deepClone();
//			String sqlNameNew = sqlName+"_new_"+time.getTime();
//			sqlNew.setName(sqlNameNew);
//			TaskContext.sqlInfoMap.put(taskName+"_new_"+time.getTime()+"_"+sqlNew.getName(), sqlNew);
//			logger.debug(taskName+"_"+sqlNew.getName());
//			srcResource.setSqlString(sqlNameNew);
			DefaultSqlContextProvider sqlContextProvider = sql.getSqlParamProvider();
			sqlContextProvider.reset();
			logger.debug(taskName+"_"+sqlName+"--"+sql);
			List<Object> paramLast = sqlContextProvider.getLastAutoParam();
			List<Object> valueLast = sqlContextProvider.getLastAutoValue();
			
			
//			DefaultSqlContextProvider sqlContextProviderNew = sqlNew.getSqlParamProvider();
//			List<Object> lastParam = sqlContextProvider.getLastAutoParam();
//			List<Object> lastValue = sqlContextProvider.getLastAutoValue();
			List<Long> paramIncreamentList = sqlContextProvider.getAutoParamIncreament();
			List<Long> valueIncreamentList = sqlContextProvider.getAutoValueIncreament();
//			for(int i = 0; i < paramBegin.size(); i++){
//				lastParam.set(i, paramBegin.get(i));
//			}
//			for(int i = 0; i < valueBegin.size(); i++){
//				lastValue.set(i, valueBegin.get(i));
//			}
			long cycles = 0;
			logger.debug("woriendfdsfdssa"+paramLast.size());
			for(int i = 0; i < paramLast.size(); i++){
				Object param = paramLast.get(i);
				logger.debug("woriendfdsfdssa");
				if(param instanceof Timestamp){
					long increament = paramIncreamentList.get(i);
					Timestamp lastTime = (Timestamp) param;
					//估算时间
					long actCycle = (time.getTime()-lastTime.getTime())/increament;
					cycles = actCycle > cycles ? actCycle : cycles;
					logger.debug("cycles="+cycles);
				}
			}
			for(int i = 0; i < valueLast.size(); i++){
				Object param = valueLast.get(i);
				if(param instanceof Date){
					long increament = valueIncreamentList.get(i);
					Date lastTime = (Date) param;
					//估算时间
					long actCycle = (time.getTime()-lastTime.getTime())/increament;
					cycles = actCycle > cycles ? actCycle : cycles;
					logger.debug("cycles="+cycles);
					
				}
			}
			logger.debug(Math.abs(cycles));
			for(int j = 0; j < Math.abs(cycles); j++){
				sqlContextProvider.updateSql(sql);
			}
		}
		
		return record;
	}
}
